<script setup lang="tsx">
import { reactive, ref } from "vue";
import { useBoolean } from "@sa/hooks";
import { jsonClone } from "@sa/utils";
import { $t } from "@/locales";
import {
  CgConfigTempletType,
  type ApiStateInput,
  type ApiSysCgConfigOut,
  type ApiSysCgConfigQuery,
} from "@/api-services";
import { feature, getAPI } from "@/axios-utils";
import {
  fetchTableQuery,
  useNetoTable,
  useTableOperate,
  useTableScroll,
} from "@/hooks/common/neto-table";
import { queryDone } from "@/utils/api";
import { SyscgconfigApi } from "@/api-services/apis/syscgconfig-api";
import syscgconfigmodal from "./modules/syscgconfig-modal.vue";
import { ElButton, ElPopconfirm } from "element-plus";
//import UserSearch from './modules/user-search.vue';

// 定义模板类型
const templetTypeMap = {
  0: "默认模板",
  1: "自定义模板",
  // 根据实际情况添加其他枚举值
};

const { tableWrapperRef, scrollConfig } = useTableScroll();
//const { bool: visible, setTrue: openModal } = useBoolean();

const apiFunc = (params: ApiSysCgConfigQuery) =>
  fetchTableQuery<ApiSysCgConfigQuery, ApiSysCgConfigOut>(
    params,
    (internalParams: ApiSysCgConfigQuery) =>
      getAPI(SyscgconfigApi).getList(internalParams),
  );
const loadingStates = ref<Record<string, boolean>>({});
type templetType = 0 | 1;
const {
  columns,
  columnChecks,
  data,
  tableSize,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams,
} = useNetoTable({
  apiFn: apiFunc,
  size: 'small',
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    keyWords: undefined,
    startDate:undefined,
    endDate:undefined,
  },
  columns: () => [
    {
      prop: "id",
      //dataIndex: "id",
      label: "编号",
      minWidth: 150,
    },
    {
      prop: "name",
      //dataIndex: "name",
      label: "名称",
      align: "center",
    },
    {
      prop: "templetType",
      //dataIndex: "templetType",
      label: "模板类型",
      align: "center",
      formatter: text => {
        return templetTypeMap[text as unknown as templetType] || '';
      }
    },
    {
      prop: "index",
      label: "操作",
      align: "center",
      minWidth: 270,
      formatter: record => {
        return (<div class="flex-center gap-8px">
          <ElButton
            type="primary"
            plain
            size="small"
            onClick={() => edit(record.id!)}
          >
            {$t("common.edit")}
          </ElButton>
          <ElButton
            type="primary"
            plain
            size="small"
            onClick={() => handleClone(record.id!)}
          >
            {$t("common.clone")}
          </ElButton>
          <ElPopconfirm
            onConfirm={() => handleDelete(record.id!)}
            title={$t("common.confirmDelete")}
          >
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>)
      }
    },
  ],
});

const {
  isVisible,
  operateType,
  editingData,
  //handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted,
} = useTableOperate(data, getData);
const edit = (id: number) => {
  // console.log(id);
  handleEdit(id);
};
const handleClone = async (id: number) => {
  // 提交请求
  const [err, res] = await feature(
    getAPI(SyscgconfigApi).clone(id),
  );

  queryDone(err, async () => {
    if (res?.data.succeeded) {
      window.$message?.success("克隆成功");
      getData();
    } else {
      window.$message?.error("克隆失败");
    }
  });
};
const handleDelete = async (id: number) => {
  const ids = [id];

  // 提交请求
  const [err, res] = await feature(
    getAPI(SyscgconfigApi).batchDelete(id.toString()),
  );

  queryDone(err, async () => {
    if (res?.data.data) {
      onDeleted();
    } else {
      window.$message?.error("删除失败");
    }
  });
};
const handleBatchDeleted = async () => {
  const ids = checkedRowKeys.value;
  if (!ids) {
    return;
  }
  // 提交请求
  const [err, res] = await feature(
    getAPI(SyscgconfigApi).batchDelete(ids.join(",")),
  );

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      window.$message?.error("删除失败");
    }
  });
};
const modalRef = ref();
function Add() {
  if (process.env.NODE_ENV === "development") console.log("Add");
  operateType.value = "add";
  //openModal();
  modalRef.value.handleInit(0, "add");
}
let dataItem = reactive<ApiSysCgConfigOut>({});
function handleEdit(id: number) {
  operateType.value = "edit";
  // const findItem = data.value.find((item) => item.id === id) || null;
  // editingData.value = jsonClone(findItem);

  modalRef.value.handleInit(id, "edit");
  //openModal();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <!-- <UserSearch
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    ></UserSearch> -->

    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.codeGenerator.sysCgConfig.title') }}</p>

          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            v-model:size="tableSize" :show-table-size="true" :loading="loading" @add="Add" @delete="handleBatchDeleted"
            @refresh="getData" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>


      <syscgconfigmodal ref="modalRef" :operate-type="operateType" :row-data="editingData" @submitted="getDataByPage" />
    </ElCard>
  </div>
</template>

<style scoped></style>
